package jane.android.lwna;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent; 
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import android.content.DialogInterface;
import android.os.Handler;  
import android.os.Message;  
import android.hardware.SensorManager;  
import android.hardware.Sensor;  
import android.hardware.SensorEventListener;  
import android.hardware.SensorEvent; 
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;


public class lwna extends Activity  {
	
    private float x, y, z; 
    private int count=1;
    Timer timer = new Timer();  
    Handler handler = new Handler(){  
    
    	
        public void handleMessage(Message msg) {  
            switch (msg.what) {      
            case 1:      
                setTitle("防盗模式开始运行");  //下面是重力感应的代码
                SensorManager sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE); 
                Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                SensorEventListener lsn = new SensorEventListener() {
        		    public void onSensorChanged(SensorEvent e) {
        		    	if(count==2){
        		    	if(
        		    	(Math.abs(SensorManager.DATA_X-x)+Math.abs(SensorManager.DATA_Y-y)+Math.abs(SensorManager.DATA_Z-z))>12)
        		    	{//播放声音的代码
        		    		Toast.makeText(lwna.this, "正在启动警报音",
        							Toast.LENGTH_LONG).show();
        		    		startService(new Intent(getBaseContext(), playing.class));  //此代码没有启动服务
        		    		
        		    		
                             count=3;
                             finish();
                                
        		    	}
        		    	}
        		    	
        		    	x = e.values[SensorManager.DATA_X];   
        		    	y = e.values[SensorManager.DATA_Y];   
        		    	z = e.values[SensorManager.DATA_Z];
        		    	if(count!=3){
        		    	count=2;}
        		    	//setTitle("x="+(int)x+","+"y="+(int)y+","+"z="+(int)z);
        		    	
        		    }
         
        		    public void onAccuracyChanged(Sensor s, int accuracy) {
        		    }
        		};
        		//注册listener，第三个参数是检测的灵敏度
        		
        		sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);
        		
        		
                break;      
            }      
            super.handleMessage(msg);  
        }  
          
    };  
    
  
    
    
    TimerTask task = new TimerTask(){  
  
        public void run() {  
            Message message = new Message();      
            message.what = 1;      
            handler.sendMessage(message);    
        }  
          
    };  
	
	//定义一个对话框的ID
	public int Edward_Movie_Dialog = 1;

	// 对话框按钮点击事件监听器
	OnClickListener ocl = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case Dialog.BUTTON_NEGATIVE:
				Toast.makeText(lwna.this, "未进入防盗模式",
						Toast.LENGTH_LONG).show();
				//finish();
				//加上退出代码
				break;
			case Dialog.BUTTON_NEUTRAL:
				Toast.makeText(lwna.this, "10秒后进入防盗模式",
						Toast.LENGTH_LONG).show();
				timer.schedule(task, 10000);  
				break;
		/*	case Dialog.BUTTON_POSITIVE:
				Toast.makeText(lwna.this, "我很喜欢他的电影。",
						Toast.LENGTH_LONG).show();
				break;*/
			}
		}
	};
	
	
	
	
	
	@Override
	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		 ActivityManager mActivityManager =    
	            (ActivityManager)getSystemService(ACTIVITY_SERVICE);   
		List<ActivityManager.RunningServiceInfo> mServiceList = mActivityManager.getRunningServices(30);   
        //我要判断的服务名字     
        final String myClassName = "jane.android.lwna.playing";   
      
        
        if(IsServiceStarted(mServiceList,myClassName)==false){
		// 定义对话框对象
		Dialog dialog = new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.btn_default).setTitle("防盗设置")
		.setMessage("是否进入防盗模式")
		.setNegativeButton("否", ocl).setNeutralButton("是", ocl).create();
		

		//显示对话框
		dialog.show();
        }else{
        	AlertDialog Builder=new AlertDialog.Builder(this).create() ;

        	Builder.setTitle("请输入解锁警报密码") ;

        	Builder.setIcon(android.R.drawable.ic_dialog_info);
        	//final EditText input= new EditText(this,(AttributeSet) android.text.method.PasswordTransformationMethod.getInstance());
            final EditText input=new EditText(this);
        	Builder.setView(input);
        	Builder.setButton("确定", new DialogInterface.OnClickListener(){
        		public void onClick(DialogInterface dialog, int which) {
        			switch (which) {
        			case Dialog.BUTTON_POSITIVE:
        				SharedPreferences  share = lwna.this.getSharedPreferences("lwna", 0); 
        				if(share.getString("pwd","").toString().equals(input.getText().toString())){
        				stopService(new Intent(getBaseContext(), playing.class));
        				finish();}
        				//读取并判断密码
        				break;
        			}
        			  }
        			}) ;
        	
            Builder.show();
        	

        }
        
		
	

	}
	
	private void pwdcommit()
	{
		AlertDialog Builder1=new AlertDialog.Builder(this).create() ;
        
    	Builder1.setTitle("请输入新密码") ;

    	Builder1.setIcon(android.R.drawable.ic_dialog_info);
    	//final EditText input1= new EditText(this,(AttributeSet) android.text.method.PasswordTransformationMethod.getInstance());
    	final EditText input1=new EditText(this);
    	Builder1.setView(input1);
    	Builder1.setButton("确定", new DialogInterface.OnClickListener(){
    		public void onClick(DialogInterface dialog, int which) {
    			switch (which) {
    			case Dialog.BUTTON_POSITIVE:
    				SharedPreferences  share = lwna.this.getSharedPreferences("lwna", 0); 
    		        Editor editor = share.edit();
    				editor.putString("pwd", input1.getText().toString());
    				editor.commit();
    				Toast.makeText(getBaseContext(), "密码已修改成功", Toast.LENGTH_LONG).show();
    				//提交新密码
    				break;
    			}
    			  }
    			}) ;
    	
        Builder1.show();
		
		
		
		
	}
	
	
	
	private boolean IsServiceStarted(List<ActivityManager.RunningServiceInfo> mServiceList,String className){   
        
        for(int i = 0; i < mServiceList.size(); i ++){   
            if(className.equals(mServiceList.get(i).service.getClassName())){   
                return true;   
            }   
        }   
        return false;   
    }   
	
	@Override  
	public boolean onCreateOptionsMenu(Menu menu) {  
	super.onCreateOptionsMenu(menu);  
	MenuInflater inflater = getMenuInflater();  
	inflater.inflate(R.menu.menu, menu);  
	return true;  
	} 
	 
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {//获取菜单项的ID，即前面Menu.add方法的第二个参数
		case R.id.changepwd:
			SharedPreferences  share = lwna.this.getSharedPreferences("lwna", 0); 
			//判断是否设置过密码
			 String pwd = share.getString("pwd", "");//根据key寻找值 参数1 key 参数2 如果没有value显示的内容  
		if(pwd==""){
				pwdcommit();
				//输入新密码并提交
			 }
			else{
				AlertDialog Builder2= new AlertDialog.Builder(this).create();
		        
		    	Builder2.setTitle("请输入原密码") ;

		    	Builder2.setIcon(android.R.drawable.ic_dialog_info);
		    	//final EditText input2= new EditText(this,(AttributeSet) android.text.method.PasswordTransformationMethod.getInstance());
		    	final EditText input2=new EditText(this);
		    	Builder2.setView(input2);
		    	Builder2.setButton("确定", new DialogInterface.OnClickListener(){
		    		public void onClick(DialogInterface dialog, int which) {
		    			switch (which) {
		    			case Dialog.BUTTON_POSITIVE:
		    				SharedPreferences  share = lwna.this.getSharedPreferences("lwna", 0); 
		    				if(share.getString("pwd","").toString().equals(input2.getText().toString())){
		    				pwdcommit();}else{
		    					Toast.makeText(getBaseContext(), "密码不正确", Toast.LENGTH_LONG).show();
		    				}
		    				
		    				//提交新密码
		    				break;
		    			}
		    			  }
		    			}) ;
		    	
		        Builder2.show();
		       
			}
			 
			 break;
			
		case R.id.about:
			AlertDialog dialog=new AlertDialog.Builder(this)
				.setTitle("关于lwna")
				.setMessage("lwna是一个在充电时使用的防盗程序，版本号1.1(为了迎接11节),任何建议或意见可以发邮件至kally11112@gmail.com,或到博客http://janelan.com留言，若此程序给您带来不便请恕我抱歉。")
			    .setIcon(android.R.drawable.btn_star)	
			    .create();
			    
			dialog.show();
			break;
		default:
			break;
		}
		return true;
	}

}



